package pl.edu.pk.mech.kkbus.controller;

import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.datastore.Key;

import java.io.IOException;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Iterator;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import pl.edu.pk.mech.kkbus.model.ResponseStatus;
import pl.edu.pk.mech.kkbus.component.MyEmailSender;
import pl.edu.pk.mech.kkbus.component.MyEntityManagerFactory;
import pl.edu.pk.mech.kkbus.entities.*;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.apache.commons.codec.digest.DigestUtils;

@Controller
@RequestMapping("/test")
public class TestController {

    private static final Logger log = Logger.getLogger(TestController.class.getName());
    
    @Autowired
    MyEmailSender emailSender;
    
    @RequestMapping(value = "/email", method = RequestMethod.GET)
    public @ResponseBody ResponseStatus sendExampleEmail() {
    
        emailSender.send("macin90@gmail.com", "KKBus", "Lorem ipsum...");
        
        return null;
    }
    
    @RequestMapping(value = "/fetch", method = RequestMethod.GET)
    public @ResponseBody ResponseStatus fetchURL() throws MalformedURLException, IOException {
        
        URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
        
        HTTPRequest request = new HTTPRequest(new URL("http://jackson.netserwer.pl/kkbus/"), HTTPMethod.POST);
        String to = "macin90@gmail.com";
        String subject = "KKBus Test";
        String message = "Lorem ipsum...";
        String body = "to=" + to + "&subject=" + subject + "&message=" + message;
        //request.setPayload(body.getBytes());
        
        fetcher.fetch(request);
        
        return null;
    }
    
    @RequestMapping(value = "/jpa/create", method = RequestMethod.GET)
    public @ResponseBody ResponseStatus jpaCreate() {
        log.info("JPA Create");
        
        EntityManagerFactory emf = MyEntityManagerFactory.get();
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            
            User user = new User();
            user.setName("Jan");
            user.setSurname("Kowalski");
            user.setBirthday(new Date());
            user.setEmail("admin@example.pl");
            user.setPassword(DigestUtils.md5Hex("qwerty123"));
            user.setHash(null);
            user.setPhone("888999777");
            user.setPoints(1000);
            user.setEnabled(true);
            
            Set<User.Role> roles = new LinkedHashSet<User.Role>();
            roles.add(User.Role.USER);
            roles.add(User.Role.ADMIN);
            user.setRoles(roles);
            
            List<HistoryLog> historyLogs = new ArrayList<HistoryLog>();
            historyLogs.add(new HistoryLog(new Date()));
            
            user.setHistoryLogs(historyLogs);
            
            em.persist(user);   
            
            Award award = new Award("Latarka", "Bardzo dobra latarka.", 1000, 9);
            
            
            log.info("Breakpoint");
        } finally {
            if (em != null)
                em.close();
        }
        
        return null;
    }
    
    @RequestMapping(value = "/jpa/get", method = RequestMethod.GET)
    public @ResponseBody ResponseStatus jpaGet() {
        log.info("JPA Get");
     
        EntityManagerFactory emf = MyEntityManagerFactory.get();
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            Query query = em.createQuery("SELECT u FROM User u");
            List<User> results = (List<User>) query.getResultList();
            Iterator<User> iterator = results.iterator();
            while (iterator.hasNext()) {
                
                User user = iterator.next();
                user.getKey().toString();
                user.getKey().getAppId();
                user.getKey().getId();
                if (user.getHistoryLogs().size() > 0) {
                    log.info("Posiada historie logowania.");
                } else {
                    log.info("NIE posiada historii logowania.");
                }
            }
            log.info("Breakpoint");
        } finally {
            if (em != null)
                em.close();
        }
        
        return null;
    }
    
    @RequestMapping(value = "/jpa/get/single", method = RequestMethod.GET)
    public @ResponseBody ResponseStatus jpaGetSingle() {
        log.info("JPA Get Single");
    
        EntityManagerFactory emf = MyEntityManagerFactory.get();
        EntityManager em = null;
        try {
            em = emf.createEntityManager();
            User user = em.find(User.class, new Long("15"));
            log.info("Breakpoint");
        } finally {
            if (em != null)
                em.close();
        }
        
        return null;
    }
}
